package com.example.annasbook.job;

import com.example.annasbook.model.BookModel;
import com.example.annasbook.processors.BookRedisListProcessor;
import com.example.annasbook.readers.BookRedisListReader;
import com.example.annasbook.repository.convert.BookConvert;
import com.example.annasbook.repository.maper.BookMapper;
import com.example.annasbook.writers.BookRedisListWriter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
public class BookListJob {
    public final JobBuilderFactory jobBuilderFactory;
    public final StepBuilderFactory stepBuilderFactory;
    public final RedissonClient redissonClient;
    public final BookMapper bookMapper;
    public final BookConvert bookConvert;

    @Bean("booklistjob")
    public Job importUserJob(Step toMysqlStep) {
        return jobBuilderFactory.get("booklist-job")
                .incrementer(new RunIdIncrementer())
                .start(toMysqlStep) //执行步骤
                .build();
    }

    @Bean("toMysqlStep")
    public Step toMysql(ItemWriter<BookModel> writer,ItemProcessor<BookModel,BookModel> processor) {
        return stepBuilderFactory.get("toMysql")
//                .tasklet(tasklet)
                .<BookModel,BookModel>chunk(3)
                .reader(reader())
                .processor(processor)
                .writer(writer)
                .build();
    }


    @Bean
    public BookRedisListReader reader() {
        return new BookRedisListReader(redissonClient);
    }


    @Bean
    public ItemProcessor<BookModel,BookModel> itemProcessor(){
        return new BookRedisListProcessor();
    }

    @Bean
    public BookRedisListWriter writer(){
        return new BookRedisListWriter(bookMapper,bookConvert);
    }
}
